<?php
namespace app\middleware;

class Cors
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        
        // 设置允许的域名（根据需求修改）
        $origin = $request->header('Origin', '*');
        $allow_origin = [
            'http://localhost:8080', // 前端开发地址
            'http://ksdtbz.7baidu.cc', // 生产环境域名
        ];

        if (in_array($origin, $allow_origin)) {
            $response->header([
                'Access-Control-Allow-Origin' => $origin,
                'Access-Control-Allow-Headers' => 'Authorization, Content-Type, X-Requested-With, Token',
                'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Credentials' => 'true', // 允许携带Cookie
            ]);
        }

        // 处理OPTIONS请求
        if ($request->method() == 'OPTIONS') {
            $response->code(204);
        }

        return $response;
    }
}